package com.nervenets.shopping.controller.order.params;

import com.nervenets.general.exception.LogicException;
import com.nervenets.general.utils.SpringContextHolder;
import com.nervenets.general.web.params.FormParams;
import com.nervenets.shopping.hibernate.domain.order.GroupBuyOrderUser;
import com.nervenets.shopping.hibernate.domain.shopping.Product;
import com.nervenets.shopping.service.GroupBuyOrderUserService;
import com.nervenets.shopping.service.ProductService;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Positive;

@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
public class GroupBuyOrderUserFormParams extends FormParams<GroupBuyOrderUser, GroupBuyOrderUserService> {
    @ApiModelProperty(value = "商品", required = true)
    @Positive
    private long productId;
    @ApiModelProperty(value = "抵扣额度")
    private int subsidy;
    @ApiModelProperty(value = "收货人", required = true)
    @NotBlank(message = "请选择收货人地址")
    private String name;
    @ApiModelProperty(value = "收货人电话", required = true)
    @NotBlank(message = "请选择收货人地址")
    private String mobile;
    @ApiModelProperty(value = "收货人地址", required = true)
    @NotBlank(message = "请选择收货人地址")
    private String address;
    @ApiModelProperty("备注")
    private String remark;

    @Override
    public GroupBuyOrderUser validateAndBuild(GroupBuyOrderUserService service, HttpServletRequest request, HttpServletResponse response) {
        Product product = SpringContextHolder.getBean(ProductService.class).findOne(productId, "您要拼团的商品不存在");
        if (!product.isEnable()) throw new LogicException("该商品已停止拼团");

        GroupBuyOrderUser orderUser = super.validateAndBuild(service, request, response);
        orderUser.setProduct(product);
        orderUser.setMoney(product.getPrice() - subsidy);
        if (orderUser.getMoney() < 0) throw new LogicException("抵扣额度不能大于商品金额。");
        return orderUser;
    }
}
